package com.kylin.upms.biz.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.kylin.upms.biz.entity.Role;
import com.kylin.upms.biz.entity.User;
import com.kylin.upms.biz.entity.UserSecurity;
import com.kylin.upms.biz.mapper.UserMapper;
import com.kylin.upms.biz.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Mht
 * @since 2019-04-11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, UserDetailsService {


    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    PasswordEncoder passwordEncoder;


    @Autowired
    UserMapper userMapper;

    @Override
    public void saveUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        this.insert(user);
    }


    @Override
    public User getUserByUsername(String username) {
        return userMapper.getUserByUsername(username);
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        logger.info("》》》》》》》》用户名:{}",s);
        User user1 =  userMapper.getUserByUsername(s);
        if (user1==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        List<Role> roles = userMapper.getRoleByUserID(user1.getId());
        String[] auths = null;
        if (roles!=null){
            auths = new String[roles.size()];
            int i = 0;
            for (Role role:roles){
                auths[i] = role.getName();
                i++;
            }
        }

        UserSecurity userSecurity = new UserSecurity(s, user1.getPassword(),AuthorityUtils.createAuthorityList(auths), user1);
        return  userSecurity;
    }
}
